<?php

namespace App\Recharge\Service;

use Exception;
use Throwable;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

/**
 * 手机归属地查询
 */
class PhoneBelongingPlaceService
{
    /**
     * url
     */
    const URL = "https://jisusjhmcx.market.alicloudapi.com/shouji/query";

    /**
     * @param string $phone 手机号
     * @return array
     */
    public function find(string $phone): array
    {
        try {
            $array = Http::withoutVerifying()
                ->withToken('328c5fe0b22d440ab3aea86bc81f9276', 'APPCODE')
                ->get(self::URL, ['shouji' => $phone])
                ->json();
            if (empty($array)) {
                throw new Exception("查询失败");
            }
            if (!isset($array['status'])) {
                throw new Exception("缺少状态码:status");
            }
            if ($array['status'] != 0) {
                throw new Exception($array['msg'] ?? ('返回状态码不为0,=' . $array['status']));
            }
            if (isset($array['result']) && !empty($array['result'])) {
                return $array['result'];
            }
            throw new Exception("未返回result参数");

        } catch (Throwable $e) {
            Log::channel('error')->error('手机号归属地查询失败',[
                'ding'  => true,
                'phone' => $phone,
                'error' => error2array($e),
            ]);
            return [];
        }
    }

}
